<template>
	<div class="cus">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1000px" @close="clean">
			<el-form ref="flowControlDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-divider :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" content-position="center">默认流量 </el-divider>
					<template v-for="(flow, index) in state.ruleForm.defaultFlow" :key="index">
						<el-col :xs="24" :sm="9" :md="9" :lg="9" :xl="9" class="mb20">
							<el-form-item label="版本" :prop="`defaultFlow[${index}].version`" :rules="rules.version">
								<el-select v-model="flow.version" class="filter-item" placeholder="键">
									<el-option v-for="item in props.itemVersions" :key="item.version" :label="item.version" :value="item.version" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="13" :md="13" :lg="13" :xl="13" class="mb20">
							<el-form-item label="流量">
								<el-slider v-model="flow.percent" :min="0" :max="100" show-input @change="updateTotalFlowPercent(index)"></el-slider>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="2" :md="2" :lg="2" :xl="2" class="mb20">
							<el-button link @click="removeDefaultFlowRecord(index)">删除</el-button>
						</el-col>
					</template>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-button type="primary" style="float: right" @click="addDefaultFlowRecord">新增</el-button>
					</el-col>
					<el-divider :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" content-position="center">高级流量 </el-divider>
					<template v-for="(flow, index) in state.ruleForm.advancedFlow" :key="index">
						<el-col :xs="24" :sm="9" :md="9" :lg="9" :xl="9" class="mb20">
							<el-form-item label="匹配类型" :prop="`advancedFlow[${index}].matchType`" :rules="rules.matchType">
								<el-select v-model="flow.matchType" class="filter-item">
									<el-option v-for="item in matchTypeOptions" :key="item.key" :label="item.displayName" :value="item.key" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
							<el-form-item label-width="0" :prop="`advancedFlow[${index}].key`" :rules="rules.key">
								<el-input v-model="flow.key" placeholder="键"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
							<el-form-item label-width="0" :prop="`advancedFlow[${index}].exp`" :rules="rules.exp">
								<el-select v-model="flow.exp" class="filter-item" placeholder="表达式">
									<el-option v-for="item in expOptions" :key="item.key" :label="item.displayName" :value="item.key" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
							<el-form-item label-width="0" :prop="`advancedFlow[${index}].value`" :rules="rules.value">
								<el-input v-model="flow.value" placeholder="值"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="9" :md="9" :lg="9" :xl="9" class="mb20">
							<el-form-item label="版本" :prop="`advancedFlow[${index}].version`" :rules="rules.version">
								<el-select v-model="flow.version" class="filter-item" placeholder="键">
									<el-option v-for="item in props.itemVersions" :key="item.version" :label="item.version" :value="item.version" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="15" :md="15" :lg="15" :xl="15" class="mb20">
							<el-button link @click="removAdvancedFlowRecord(index)">删除</el-button>
						</el-col>
					</template>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-button type="primary" style="float: right" @click="addAdvancedFlowRecord">新增</el-button>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit()" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="flowControlDialog">
import { reactive, onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { flowControlApi } from '/@/api/flowControl';
import type { FormInstance } from 'element-plus';

// 定义变量内容
const flowControlDialogFormRef = ref<FormInstance>();

const matchTypeOptions = [
	{ key: 'headers', displayName: 'headers' },
	{ key: 'uri', displayName: 'uri' },
	{ key: 'scheme', displayName: 'scheme' },
	{ key: 'method', displayName: 'method' },
	{ key: 'authority', displayName: 'authority' },
];

const expOptions = [
	{ key: 'exact', displayName: 'exact' },
	{ key: 'prefix', displayName: 'prefix' },
	{ key: 'regex', displayName: 'regex' },
];

const rules = reactive({
	version: [{ required: true, message: '版本必选', trigger: 'blur' }],
	matchType: [{ required: true, message: '匹配类型必选', trigger: 'blur' }],
	key: { required: true, message: '键必填', trigger: 'blur' },
	exp: [{ required: true, message: '表达式必选', trigger: 'blur' }],
	value: [{ required: true, message: '值必填', trigger: 'blur' }],
	'state.ruleForm.advancedFlow.*.key': [{ required: true, message: '键必填', trigger: 'blur' }],
});

const props = defineProps({
	itemVersions: {
		type: Array,
		default: () => [],
	},
});

const state = reactive({
	ruleForm: {
		id: undefined,
		itemId: undefined,
		defaultFlow: [],
		advancedFlow: [],
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '流量控制',
		submitTxt: '确定',
		operatorNode: undefined,
		operatorNodeData: undefined,
	},
});

// 打开弹窗
const openDialog = async (clickNode?: any) => {
	state.dialog.isShowDialog = true;
	state.dialog.operatorNode = clickNode;
	state.dialog.operatorNodeData = clickNode.data;
	nextTick(() => {
		getData();
	});
};

// 清空表单
const clean = () => {
	state.ruleForm = {
		id: undefined,
		itemId: undefined,
		defaultFlow: [],
		advancedFlow: [],
	};
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	flowControlDialogFormRef.value.validate((valid: boolean) => {
		if (valid) {
			flowControlApi()
				.updateFlowControle(state.ruleForm)
				.then(() => {
					ElMessage.success('保存成功');
					closeDialog(); // 关闭弹窗
				})
				.catch((err) => {
					ElMessage.error(err.msg);
				});
		}
	});
};

const getData = async () => {
	flowControlApi()
		.getFlowControle(state.dialog.operatorNodeData.id)
		.then((res) => {
			state.ruleForm = res.data;
		})
		.catch((err) => {
			ElMessage.error(err.msg);
		});
};

const updateTotalFlowPercent = (index) => {
	const totalTraffic = state.ruleForm.defaultFlow.reduce((total, item) => total + item.percent, 0);
	if (totalTraffic > 100) {
		let diff = totalTraffic - 100;
		const defaultFlow = state.ruleForm.defaultFlow;
		let excludeIndexFlows = defaultFlow.filter((item, i) => i != index);
		excludeIndexFlows.some((item) => {
			const p = item.percent;
			if (p - diff >= 0) {
				item.percent -= diff;
				return true;
			} else {
				item.percent -= p;
				diff = diff - p;
			}
		});
	} else if (totalTraffic < 100 && totalTraffic > 0) {
		let diff = 100 - totalTraffic;
		let flow = state.ruleForm.defaultFlow.filter((item, i) => i != index)[0];
		flow.percent += diff;
	}
};

const removeDefaultFlowRecord = (index) => {
	if (state.ruleForm.defaultFlow.length == 1) {
		ElMessage.warning('默认流量控制不能少于1条');
		return;
	}
	state.ruleForm.defaultFlow[index].percent = 0;
	updateTotalFlowPercent(index);
	state.ruleForm.defaultFlow.splice(index, 1);
};

const addDefaultFlowRecord = () => {
	//验证
	if (state.ruleForm.defaultFlow.length == props.itemVersions.length) {
		ElMessage.warning('默认流量控制不能超过版本数量');
		return;
	}
	state.ruleForm.defaultFlow.push({ version: '', percent: 0 });
};

const removAdvancedFlowRecord = (index) => {
	state.ruleForm.advancedFlow.splice(index, 1);
};

const addAdvancedFlowRecord = () => {
	state.ruleForm.advancedFlow.push({ matchType: 'headers', key: '', exp: 'exact', value: '', version: '' });
};

// 页面加载时
onMounted(() => {
	// getData();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
.cus:deep(.el-overlay .el-overlay-dialog) {
	align-items: normal;

	.el-dialog {
		margin: 15vh auto !important;
	}
}

/* 删除按钮样式 */
:deep(.el-button.is-link) {
	padding: 4px 12px;
	background-color: #fff2f0;
	border: 1px solid #ffccc7;
	border-radius: 4px;
	color: #ff4d4f;
	font-size: 12px;
	transition: all 0.2s ease;
}

:deep(.el-button.is-link:hover) {
	background-color: #ff4d4f;
	border-color: #ff4d4f;
	color: #fff;
	transform: translateY(-1px);
	box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
}

:deep(.el-button.is-link:active) {
	transform: translateY(0);
	box-shadow: 0 1px 2px rgba(255, 77, 79, 0.3);
}
</style>
